package com.ms.controller;

import com.ms.entity.User;
import com.ms.entity.Volunteer;
import com.ms.entity.VolunteerActivity;
import com.ms.entity.VolunteerEnroll;
import com.ms.service.inter.VolunteerActivityService;
import com.ms.service.inter.VolunteerEnrollService;
import com.ms.service.inter.VolunteerService;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 志愿者活动报名控制器
 */
@RestController
@RequestMapping("/ve")
public class VolunteerEnrollController {

    @Autowired
    private VolunteerEnrollService volunteerEnrollService;
    
    @Autowired
    private VolunteerService volunteerService;
    
    @Autowired
    private VolunteerActivityService volunteerActivityService;

    /**
     * 添加报名记录
     * @param volunteerEnroll 报名信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addVolunteerEnroll(@RequestBody VolunteerEnroll volunteerEnroll) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = volunteerEnrollService.addVolunteerEnroll(volunteerEnroll);
            result.put("success", success);
            if (success) {
                result.put("message", "报名成功");
            } else {
                result.put("message", "报名失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "报名失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除报名记录
     * @param enrollId 报名记录ID
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteVolunteerEnroll(@RequestParam Long enrollId) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = volunteerEnrollService.deleteVolunteerEnrollById(enrollId);
            result.put("success", success);
            if (success) {
                result.put("message", "删除成功");
            } else {
                result.put("message", "删除失败，记录不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新报名记录
     * @param volunteerEnroll 报名信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateVolunteerEnroll(@RequestBody VolunteerEnroll volunteerEnroll) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = volunteerEnrollService.updateVolunteerEnroll(volunteerEnroll);
            result.put("success", success);
            if (success) {
                result.put("message", "更新成功");
            } else {
                result.put("message", "更新失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID获取报名记录
     * @param enrollId 报名记录ID
     * @return 报名记录详情
     */
    @GetMapping("/detail")
    public ResponseEntity<Map<String, Object>> getVolunteerEnroll(@RequestParam Long enrollId) {
        Map<String, Object> result = new HashMap<>();

        try {
            VolunteerEnroll volunteerEnroll = volunteerEnrollService.getVolunteerEnrollById(enrollId);
            if (volunteerEnroll != null) {
                result.put("success", true);
                result.put("data", volunteerEnroll);
            } else {
                result.put("success", false);
                result.put("message", "记录不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有报名记录
     * @return 所有报名记录列表
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllVolunteerEnrolls() {
        Map<String, Object> result = new HashMap<>();

        try {
            List<VolunteerEnroll> volunteerEnrolls = volunteerEnrollService.getAllVolunteerEnrolls();
            result.put("success", true);
            result.put("data", volunteerEnrolls);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据志愿者ID获取报名记录
     * @param volunteerId 志愿者ID
     * @return 报名记录列表
     */
    @GetMapping("/byVolunteer")
    public ResponseEntity<Map<String, Object>> getVolunteerEnrollsByVolunteerId(@RequestParam Long volunteerId) {
        Map<String, Object> result = new HashMap<>();

        try {
            List<VolunteerEnroll> volunteerEnrolls = volunteerEnrollService.getVolunteerEnrollsByVolunteerId(volunteerId);
            // 根据志愿者ID获取志愿者信息
            Volunteer volunteer = volunteerService.findById(Math.toIntExact(volunteerId));
            result.put("success", true);
            result.put("data", volunteerEnrolls);
            if (volunteer != null) {
                result.put("volunteer", volunteer);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据活动ID获取报名记录
     * @param activityId 活动ID
     * @return 报名记录列表
     */
    @GetMapping("/byActivity")
    public ResponseEntity<Map<String, Object>> getVolunteerEnrollsByActivityId(@RequestParam Long activityId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<VolunteerEnroll> volunteerEnrolls = volunteerEnrollService.getVolunteerEnrollsByActivityId(activityId);
            // 创建一个Map来存储志愿者信息，key为志愿者ID，value为志愿者对象
            Map<Long, Volunteer> volunteerMap = new HashMap<>();
            
            // 遍历报名记录，获取所有相关的志愿者信息
            for (VolunteerEnroll enroll : volunteerEnrolls) {
                Long volunteerId = enroll.getVolunteerId();
                if (!volunteerMap.containsKey(volunteerId)) {
                    Volunteer volunteer = volunteerService.findById(Math.toIntExact(volunteerId));
                    if (volunteer != null) {
                        volunteerMap.put(volunteerId, volunteer);
                    }
                }
            }
            
            result.put("success", true);
            result.put("data", volunteerEnrolls);
            result.put("volunteers", volunteerMap);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 通过报名申请
     * @param enrollId 报名记录ID
     * @return 处理结果
     */
    @PutMapping("/approve")
    public ResponseEntity<Map<String, Object>> approveEnroll(@RequestParam Long enrollId) {
        Map<String, Object> result = new HashMap<>();
        System.out.println("使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口使用了这个接口");
        try {
            boolean success = volunteerEnrollService.approveEnroll(enrollId);
            result.put("success", true);
            result.put("message", "报名申请已通过");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 取消通过的报名申请
     * @param enrollId 报名记录ID
     * @return 处理结果
     */
    @PutMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelEnroll(@RequestParam Long enrollId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = volunteerEnrollService.cancelEnroll(enrollId);
            if (success) {
                result.put("success", true);
                result.put("message", "报名申请已取消");
            } else {
                result.put("success", false);
                result.put("message", "取消失败，报名记录不存在或未通过审核");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 拒绝报名申请
     * @param enrollId 报名记录ID
     * @return 处理结果
     */
    @PutMapping("/reject")
    public ResponseEntity<Map<String, Object>> rejectEnroll(@RequestParam Long enrollId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = volunteerEnrollService.rejectEnroll(enrollId);
            if (success) {
                result.put("success", true);
                result.put("message", "报名申请已拒绝");
            } else {
                result.put("success", false);
                result.put("message", "拒绝失败，报名记录不存在或状态不正确");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 志愿者申请参加志愿活动
     * 用户必须经过管理员审批且状态为"已通过"后，才能申请参加志愿者活动
     * @param activityId 活动ID
     * @param request HTTP请求
     * @return 申请结果
     */
    @PostMapping("/applyForActivity")
    public ResponseEntity<Map<String, Object>> applyForVolunteerActivity(
            @RequestParam Long activityId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;

            // 检查用户是否是已通过审批的志愿者
            Volunteer volunteer = volunteerService.findByUserId(currentUser.getUserID());
            if (volunteer == null || !"approved".equals(volunteer.getStatus())) {
                result.put("success", false);
                result.put("message", "您不是已通过审批的志愿者，无法申请参加活动");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查活动是否存在且状态为招募中
            VolunteerActivity activity = volunteerActivityService.findById(activityId);
            if (activity == null) {
                result.put("success", false);
                result.put("message", "活动不存在");
                return ResponseEntity.badRequest().body(result);
            }

            if (activity.getStatus() != 1) { // 1表示招募中
                result.put("success", false);
                result.put("message", "活动不在招募中状态");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查是否已经申请过该活动
            VolunteerEnroll existingEnroll = volunteerEnrollService.getVolunteerEnrollByVolunteerIdAndActivityId(
                    volunteer.getVolunteerID().longValue(), activityId);
            if (existingEnroll != null) {
                result.put("success", false);
                result.put("message", "您已经申请过该活动了");
                return ResponseEntity.badRequest().body(result);
            }

            // 创建报名记录
            VolunteerEnroll enroll = new VolunteerEnroll();
            enroll.setVolunteerId(volunteer.getVolunteerID().longValue());
            enroll.setActivityId(activityId);
            enroll.setEnrollStatus(0); // 0表示待审核
            enroll.setEnrollTime(LocalDateTime.now());

            boolean success = volunteerEnrollService.addVolunteerEnroll(enroll);
            if (success) {
                result.put("success", true);
                result.put("message", "申请成功，请等待审核");
            } else {
                result.put("success", false);
                result.put("message", "申请失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "申请失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}